package com.lagou.rocket.service;

import com.lagou.rocket.dao.WarehouseDao;
import com.lagou.rocket.entity.Order;
import com.lagou.rocket.entity.Warehouse;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@Service
public class WarehouseService {

    @Autowired
    private WarehouseDao warehouseDao;

    @Autowired
    private StringRedisTemplate redisTemplate;


    public boolean hasStock(String goods, Integer num) {
        String key = "stock:" + goods;
        Object value = redisTemplate.opsForValue().get(key);
        //先检查 库存是否充足
        Integer stock = Integer.valueOf(value.toString());
        if (stock < num) {
            return false;
        }
        return true;
    }

    public void stock(String goods, Integer num) {
        String key = "stock:" + goods;
        redisTemplate.opsForValue().increment(key, num);

    }

    public synchronized void realstock(String goods, Integer num) {

        Warehouse probe = new Warehouse();
        probe.setName(goods);
        Optional<Warehouse> one = warehouseDao.findOne(Example.of(probe));
        if (one.isPresent()) {
            Warehouse warehouse = one.get();
            warehouse.setRemain(warehouse.getRemain() + num);
            warehouseDao.save(warehouse);
        }
    }



    @PostConstruct
    public void initStock() {
        Warehouse probe = new Warehouse();
        probe.setName("LagouPhone");
        Optional<Warehouse> one = warehouseDao.findOne(Example.of(probe));
        Warehouse warehouse = one.get();
        redisTemplate.opsForValue().set("stock:" + warehouse.getName(), warehouse.getRemain() + "");
    }
}
